/*
package com.pie4cloud.pie.job.executor.job;

import com.alibaba.fastjson.JSON;
import com.pie4cloud.pie.bus.api.consumer.MetricCalcService;
import com.pie4cloud.pie.bus.api.consumer.annotation.KfkConsumer;
import com.pie4cloud.pie.bus.api.dto.MessageDto;
import com.pie4cloud.pie.common.core.util.R;
import com.pie4cloud.pie.job.api.consumer.IHanlderConsumer;
import com.pie4cloud.pie.job.api.consumer.annotation.Hanlder;
import com.pie4cloud.pie.job.api.dto.CallBackDto;

import com.pie4cloud.pie.job.api.entity.JobInfoEntity;
import com.pie4cloud.pie.job.api.entity.ConfigFtp;
import com.pie4cloud.pie.job.api.vo.MybatisVo;
import com.pie4cloud.pie.job.api.vo.ResVo;
import com.pie4cloud.pie.job.api.vo.WhenTimeVo;
import com.pie4cloud.pie.job.executor.mapper.MybatisQueryMapper;
import com.pie4cloud.pie.job.executor.utils.DateExpressionEngine;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
//@Hanlder(handler = "dispenseHandler")
public class DispenseHandlerService implements IHanlderConsumer {
	@Autowired
	private MetricCalcService metricCalcService;
	private final MybatisQueryMapper mybatisQueryMapper;
	protected static final String REGEX = "(\\#\\{(.*?)\\})";
	protected static final Pattern PATTERN = Pattern.compile(REGEX);

	@Override
	public R execute(String jobInfoEntity, CallBackDto callBackDto) throws Exception {
		R<String> result= null;
		DispenseEntity dispenseEntity=JSON.parseObject(jobInfoEntity,DispenseEntity.class);
		try {
			result = R.ok();
			if(dispenseEntity.getCollectType()==0){
				this.executeByDataBase(dispenseEntity,result);
			}else {
				this.executeByNas(dispenseEntity,result);
			}
			if(0!=result.getCode()){
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			dispenseEntity.setSourceFileName(null);
			dispenseEntity.setSourceDirectory(null);
			dispenseEntity.setTargetDirectory(null);
			dispenseEntity.setTargetFileName(null);
			callBackDto.setParams(JSON.toJSONString(dispenseEntity));
		}
		return result;
	}

	public void executeByDataBase(DispenseEntity dispenseEntity,R<String> result){
		String topic="DISPENSE_"+dispenseEntity.getDdataId()+"_"+dispenseEntity.getId();
		if(1==dispenseEntity.getIsHistory()){
			Date historyStartTime=dispenseEntity.getHistoryStartTime();
			*/
/*if(null!=dispenseEntity.getHistoryNowTime()){
				historyStartTime=dispenseEntity.getHistoryNowTime();
			}*//*

			Date whenTime=new Date(historyStartTime.getTime());
			List<WhenTimeVo> whenTimeVos=new ArrayList<>();
			while(whenTime.getTime()<dispenseEntity.getHistoryEndTime().getTime()){
				WhenTimeVo whenTimeVo=new WhenTimeVo();
				Date nextTime=this.getNextTriggerTime(dispenseEntity.getJobCron(),whenTime);
				if((nextTime.getTime()-whenTime.getTime())<60*60*1000){
					nextTime=new Date(whenTime.getTime()+60*1000*60*24);
				}
				if(nextTime.getTime()>=dispenseEntity.getHistoryEndTime().getTime()){
					whenTimeVo.setWhenTime(whenTime.getTime());
					whenTimeVo.setEndTime(dispenseEntity.getHistoryEndTime().getTime());
					whenTimeVo.setStartTime(whenTime.getTime());
					whenTimeVos.add(whenTimeVo);
					break;
				}else {
					whenTimeVo.setWhenTime(whenTime.getTime());
					whenTimeVo.setEndTime(nextTime.getTime());
					whenTimeVo.setStartTime(whenTime.getTime());
					whenTimeVos.add(whenTimeVo);
				}
				whenTime=nextTime;
			}
			Date historyNowTime= this.computingTime(dispenseEntity,whenTimeVos,topic,result);
			dispenseEntity.setHistoryNowTime(historyNowTime);
		}

		List<WhenTimeVo> whenTimeVos=new ArrayList<>();
		WhenTimeVo whenTimeVo=new WhenTimeVo();
		whenTimeVo.setEndTime(dispenseEntity.getTriggerNextTime());
		whenTimeVo.setStartTime(dispenseEntity.getTriggerLastTime());
		whenTimeVo.setWhenTime(dispenseEntity.getTriggerLastTime());
		whenTimeVos.add(whenTimeVo);
		Date realNowTime= this.computingTime(dispenseEntity,whenTimeVos,topic,result);
		dispenseEntity.setRealNowTime(realNowTime);
	}
	public Date computingTime(DispenseEntity dispenseEntity,List<WhenTimeVo> whenTimeVos,String topic,R<String> result){
		    Date blockTime=null;
			for(WhenTimeVo whenTimeVo:whenTimeVos) {
				MybatisVo mybatisVo = new MybatisVo();
				mybatisVo.setDdataId("'" + dispenseEntity.getDdataId() + "'");
				mybatisVo.setTableName(dispenseEntity.getTableName());
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				mybatisVo.setBeginTime("'" + simpleDateFormat.format(whenTimeVo.getStartTime()) + "'");
				mybatisVo.setEndTime("'" + simpleDateFormat.format(whenTimeVo.getEndTime()) + "'");
				List<Map<String, Object>> maps = mybatisQueryMapper.selectFidbInfo(mybatisVo, "ht_fidb");
				ResVo resVo=new ResVo();
				String filePath = DateExpressionEngine.formatDateExpression(dispenseEntity.getSourceFileName(),whenTimeVo.getWhenTime());
				Matcher m = PATTERN.matcher(filePath);
				while (m.find()) {
					String expression = m.group(2);
					String replaceMent = expression.split(",")[0].replaceAll("[ymdhsYMDHS]", "\\\\d");
					filePath = filePath.replace("#{" + expression + "}", replaceMent);
					resVo.setFormat(expression);
					resVo.setRes(replaceMent);
				}
				resVo.setIndex(this.getLocation(filePath,resVo.getRes()));
				resVo.setSourceFileName(filePath);
				if (null != maps && maps.size() > 0) {
					for (Map<String, Object> map : maps) {
						//String name= "D:/"+(String) map.get("D_STORAGE_SITE");
						String name = (String) map.get("D_STORAGE_SITE");
						File file = new File(name);
						List<String> patternList=this.getPatternList(name,Pattern.compile(resVo.getSourceFileName()));
						List<String> parentheses=this.getParentheses(dispenseEntity.getTargetDirectory());
						long datatime=whenTimeVo.getWhenTime();
						if(StringUtils.isNotEmpty(resVo.getRes())){
							SimpleDateFormat simpleDateFormat1=new SimpleDateFormat(resVo.getFormat());
							try {
								datatime=simpleDateFormat1.parse(patternList.get(resVo.getIndex())).getTime();
							} catch (Exception e) {
								e.printStackTrace();
							}
							if(datatime<whenTimeVo.getStartTime()||datatime>=whenTimeVo.getEndTime()){
								continue;
							}
						}
						map.put("dateTime",datatime);
						String targetDirectory=DateExpressionEngine.formatDateExpression(dispenseEntity.getTargetDirectory(),datatime);
						String fileName=file.getName();
						String targetFileName=DateExpressionEngine.formatDateExpression(dispenseEntity.getTargetFileName(),datatime);
						if(StringUtils.isNotEmpty(targetFileName)){
							fileName=targetFileName;
						}
						if(patternList.size()>0&&parentheses.size()>0){
							for(int i=0;i<patternList.size();i++){
								targetDirectory=targetDirectory.replaceAll("\\("+i+"\\)",patternList.get(i));
								if(StringUtils.isNotEmpty(targetFileName)){
									fileName=fileName.replaceAll("\\("+i+"\\)",patternList.get(i));
								}
							}

						}else {
							targetDirectory=file.getParentFile().getAbsolutePath().replaceAll("\\\\","/").replaceAll(dispenseEntity.getSourceDirectory(),dispenseEntity.getTargetDirectory());
						}

						map.put("D_STORAGE_SITE",name);
						map.put("sourceDirectory",dispenseEntity.getSourceDirectory());
						map.put("targetDirectory",targetDirectory);
						map.put("fileName",fileName);
						map.put("whenTime",whenTimeVo.getWhenTime());
						map.put("ftp",dispenseEntity.getConfigFtp());
						this.excuteKaf(map,topic);
					}
					blockTime=new Date(whenTimeVo.getWhenTime());
				}

			}
		return blockTime;
	}
	public Date computingTimeFolder(DispenseEntity dispenseEntity,List<WhenTimeVo> whenTimeVos,String topic,R<String> result){
		Date blockTime=null;
		try {
                for(WhenTimeVo whenTimeVo:whenTimeVos){
					List<String> folderParentheses=this.getParentheses(dispenseEntity.getSourceDirectory());
					List<String> folderList=new ArrayList<>();
					String sourceDirectory=DateExpressionEngine.formatDateExpression(dispenseEntity.getSourceDirectory(),whenTimeVo.getWhenTime());
					folderList.add(sourceDirectory);
					for(int i=0;i<folderParentheses.size();i++){
						String[] folderP=folderParentheses.get(i).split("\\|");
						List<String> folderListP=new ArrayList<>();
						for(int j=0;j<folderP.length;j++){
							for(int k=0;k<folderList.size();k++){
								folderListP.add(folderList.get(k).replaceAll("\\("+StringUtils.join(folderP, "\\|")+"\\)",folderP[j]));
							}
						}
						folderList.clear();
						folderList.addAll(folderListP);
					}
					for(String folder:folderList){
						ResVo resVo=new ResVo();
						resVo.setSourceDirectory(folder);
						List<Path> paths=this.fileList(dispenseEntity,whenTimeVo,resVo);
						if(null!=paths&&paths.size()>0){
							for(Path path:paths){
								Map<String,Object> map=new HashMap<>();
								File file=path.toFile();
								String name=file.getPath().replaceAll("\\\\","/");
								List<String> patternList=this.getPatternList(name,Pattern.compile(resVo.getSourceFileName()));
								List<String> parentheses=this.getParentheses(dispenseEntity.getTargetDirectory());
								long datatime=whenTimeVo.getWhenTime();
								if(StringUtils.isNotEmpty(resVo.getRes())){
									SimpleDateFormat simpleDateFormat=new SimpleDateFormat(resVo.getFormat());
									datatime=simpleDateFormat.parse(patternList.get(resVo.getIndex())).getTime();
									if(datatime<whenTimeVo.getStartTime()||datatime>=whenTimeVo.getEndTime()){
										continue;
									}
								}
								map.put("dateTime",datatime);
								String targetDirectory=DateExpressionEngine.formatDateExpression(dispenseEntity.getTargetDirectory(),datatime);
								String fileName=file.getName();
								String targetFileName=DateExpressionEngine.formatDateExpression(dispenseEntity.getTargetFileName(),datatime);
								if(StringUtils.isNotEmpty(targetFileName)){
									fileName=targetFileName;
								}
								if(patternList.size()>0&&parentheses.size()>0){
									for(int i=0;i<patternList.size();i++){
										targetDirectory=targetDirectory.replaceAll("\\("+i+"\\)",patternList.get(i));
										if(StringUtils.isNotEmpty(targetFileName)){
											fileName=fileName.replaceAll("\\("+i+"\\)",patternList.get(i));
										}
									}

								}else {
									targetDirectory=file.getParentFile().getAbsolutePath().replaceAll("\\\\","/").replaceAll(dispenseEntity.getSourceDirectory(),dispenseEntity.getTargetDirectory());
								}

								map.put("D_STORAGE_SITE",name);
								map.put("sourceDirectory",dispenseEntity.getSourceDirectory());
								map.put("targetDirectory",targetDirectory);
								map.put("fileName",fileName);
								map.put("whenTime",whenTimeVo.getWhenTime());
								map.put("ftp",dispenseEntity.getConfigFtp());
								this.excuteKaf(map,topic);
							}
							blockTime=new Date(whenTimeVo.getWhenTime());
						}

					}

				}


		} catch (Exception e) {
			e.printStackTrace();
		}
		return blockTime;
	}

	public void excuteKaf(Map<String,Object> maps,String topic){
		List<MessageDto> messageDtos=new ArrayList<>();
		MessageDto messageDto=new MessageDto();
		messageDto.setContent(JSON.toJSONString(maps));
		messageDto.setTopic(topic);
		messageDtos.add(messageDto);
		metricCalcService.submit(messageDtos);
	}

*/
/*
	public  void writeFile(String content, String fileName) {

		// 在文件夹目录下新建文件
		File file = new File(fileName);

		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
        if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		try {
			if (!file.exists()) {
				boolean hasFile = file.createNewFile();
				if (hasFile) {
					log.info("file not exists, create new file");
				}
				fos = new FileOutputStream(file);
			} else {
				fos = new FileOutputStream(file, true);
			}

			osw = new OutputStreamWriter(fos, "utf-8");
			// 写入内容
			osw.write(content);
			// 换行
			osw.write("\r\n");
			log.info("成功向文件 [{}] 写入内容：[{}]", fileName, content);
		} catch (Exception e) {
			log.info("写入文件发生异常", e);
		} finally {
			// 关闭流
			try {
				if (osw != null) {
					osw.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				log.info("关闭流异常", e);
			}
		}
	}
*//*

	public void executeByNas(DispenseEntity dispenseEntity,R<String> result) {
		String topic = "DISPENSE_" + dispenseEntity.getDdataId() + "_" + dispenseEntity.getId();
		if(1==dispenseEntity.getIsHistory()){
			Date historyStartTime=dispenseEntity.getHistoryStartTime();
			*/
/*if(null!=dispenseEntity.getHistoryNowTime()){
				historyStartTime=dispenseEntity.getHistoryNowTime();
			}*//*

			Date whenTime=new Date(historyStartTime.getTime());
			List<WhenTimeVo> whenTimeVos=new ArrayList<>();
			while(whenTime.getTime()<dispenseEntity.getHistoryEndTime().getTime()){
				WhenTimeVo whenTimeVo=new WhenTimeVo();
				Date nextTime=this.getNextTriggerTime(dispenseEntity.getJobCron(),whenTime);
				if((nextTime.getTime()-whenTime.getTime())<60*60*1000){
					nextTime=new Date(whenTime.getTime()+60*1000*60*24);
				}
				if(nextTime.getTime()>=dispenseEntity.getHistoryEndTime().getTime()){
					whenTimeVo.setWhenTime(whenTime.getTime());
					whenTimeVo.setEndTime(dispenseEntity.getHistoryEndTime().getTime());
					whenTimeVo.setStartTime(whenTime.getTime());
					whenTimeVos.add(whenTimeVo);
					break;
				}else {
					whenTimeVo.setWhenTime(whenTime.getTime());
					whenTimeVo.setEndTime(nextTime.getTime());
					whenTimeVo.setStartTime(whenTime.getTime());
					whenTimeVos.add(whenTimeVo);
				}
				whenTime=nextTime;
			}
			Date historyNowTime= this.computingTimeFolder(dispenseEntity,whenTimeVos,topic,result);
			dispenseEntity.setHistoryNowTime(historyNowTime);
		}

		List<WhenTimeVo> whenTimeVos=new ArrayList<>();
		WhenTimeVo whenTimeVo=new WhenTimeVo();
		whenTimeVo.setEndTime(dispenseEntity.getTriggerNextTime());
		whenTimeVo.setStartTime(dispenseEntity.getTriggerLastTime());
		whenTimeVo.setWhenTime(dispenseEntity.getTriggerLastTime());
		whenTimeVos.add(whenTimeVo);
		Date realNowTime= this.computingTimeFolder(dispenseEntity,whenTimeVos,topic,result);
		dispenseEntity.setRealNowTime(realNowTime);

	}

    public List<Path> fileList(DispenseEntity dispenseEntity,WhenTimeVo whenTimeVo,ResVo resVo){
		if(!new File(resVo.getSourceDirectory()).exists()){
			return new ArrayList<>();
		}
		Path pathSource = Paths.get(resVo.getSourceDirectory());
		String sourceFileName=dispenseEntity.getSourceFileName();
		List<Path> paths = null;
		try {
			String filePath = DateExpressionEngine.formatDateExpression(sourceFileName,whenTimeVo.getWhenTime());
			Matcher m = PATTERN.matcher(filePath);
			while (m.find()) {
				String expression = m.group(2);
				String replaceMent = expression.split(",")[0].replaceAll("[ymdhsYMDHS]", "\\\\d");
				filePath = filePath.replace("#{" + expression + "}", replaceMent);
				resVo.setFormat(expression);
				resVo.setRes(replaceMent);
			}
			resVo.setIndex(this.getLocation(filePath,resVo.getRes()));
			resVo.setSourceFileName(filePath);
			Pattern pattern = Pattern.compile(filePath);
			paths = Files.walk(pathSource).filter(p -> {
				//如果不是普通的文件，则过滤掉
				if(!Files.isRegularFile(p)) {
					return false;
				}
				File file = p.toFile();
				String path=file.getAbsolutePath().replaceAll("\\\\","/");
				Matcher matcher = pattern.matcher(path);
				return matcher.find();
			}).collect(Collectors.toList());
		}  catch (IOException e) {
			e.printStackTrace();
		}
		if(paths==null){
			paths=new ArrayList<>();
		}
		return paths;

	}
	public  List<String> getPatternList(String managers,Pattern pattern){
		List<String> ls=new ArrayList<String>();
		Matcher matcher = pattern.matcher(managers);
		while(matcher.find())
			for (int j = 1; j <= matcher.groupCount(); j++){
				String timeStr = matcher.group(j);
				ls.add(timeStr);
			}
		return ls;
	}
	public int getLocation(String str,String value){
		List<String> ls=new ArrayList<String>();
		String regex = "(?<=\\()(.+?)(?=\\))";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		//System.out.println("replace: "+str.replaceAll(regex, "O"));
		int k=-1;
		while (matcher.find()) {
			for (int j = 1; j <= matcher.groupCount(); j++){
				k++;
				String timeStr = matcher.group(j);
				if(timeStr.equals(value)){
					return k;
				}
			}
		}
		return k;
	};
	public List<String> getParentheses(String str){
		List<String> ls=new ArrayList<String>();
		String regex = "(?<=\\()(.+?)(?=\\))";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		//System.out.println("replace: "+str.replaceAll(regex, "O"));
		while (matcher.find()) {
			for (int j = 1; j <= matcher.groupCount(); j++){
				String timeStr = matcher.group(j);
				ls.add(timeStr);
			}
		}
		return ls;
	};

	public  Date getLastTriggerTime(String cron,Date date){
		CronExpression  cronExpression =CronExpression.parse(cron);
		ZoneId zoneId = ZoneId.systemDefault();
		LocalDateTime time1 = cronExpression.next(LocalDateTime.ofInstant(date.toInstant(), zoneId));//下次执行时间
		LocalDateTime time2 = cronExpression.next(time1);
		LocalDateTime time3 = cronExpression.next(time2);
		long l =  Date.from(time1.atZone(zoneId).toInstant()).getTime() -(Date.from(time3.atZone(zoneId).toInstant()).getTime() -Date.from(time2.atZone(zoneId).toInstant()).getTime());
		Date date1 = new Date(l);
		return date1;
	}

	public  Date getNextTriggerTime(String cron,Date date){
		if(StringUtils.isEmpty(cron)){
			return date;
		}
		CronExpression  cronExpression =CronExpression.parse(cron);
		ZoneId zoneId = ZoneId.systemDefault();
		LocalDateTime time1 = cronExpression.next(LocalDateTime.ofInstant(date.toInstant(), zoneId));//下次执行时间
		return Date.from(time1.atZone(zoneId).toInstant());
	}

}
*/
